package com.hainingtong.miniapp.controller;

import com.hainingtong.busapi.BusApi;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/mini/bus")
public class BusController {

    @Resource
    private Environment env;

    @GetMapping("/xfyun/auth/url")
    public Map<String, String> getAuthUrl() throws Exception {
        String hostUrl = env.getProperty("xfyun.host");
        String apiKey = env.getProperty("xfyun.app-key");
        String apiSecret = env.getProperty("xfyun.app-secret");

        URL url = new URL(hostUrl);
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        StringBuilder builder = new StringBuilder("host: ").append(url.getHost()).append("\n").//
                append("date: ").append(date).append("\n").//
                append("GET ").append(url.getPath()).append(" HTTP/1.1");
        //System.out.println(builder);
        Charset charset = Charset.forName("UTF-8");
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(charset), "hmacsha256");
        mac.init(spec);
        byte[] hexDigits = mac.doFinal(builder.toString().getBytes(charset));
        String sha = Base64.getEncoder().encodeToString(hexDigits);

        //System.out.println(sha);
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        //System.out.println(authorization);

        String httpUrl = "wss://" + url.getHost() + url.getPath()
                + "?authorization=" + Base64.getEncoder().encodeToString(authorization.getBytes(charset))
                + "&date=" + date
                + "&host=" + url.getHost();

        HashMap<String, String> res = new HashMap<>();
        res.put("url", httpUrl);
        return res;
    }

    @GetMapping("search")
    Object search(@RequestParam String name) {
        return BusApi.busSearch(name);
    }

    @GetMapping("/busWithStation/{id}")
    Object busWithDirectionByStation(@PathVariable String id) {
        return BusApi.busWithDirectionByStation(id);
    }

    @GetMapping("/queryBus/{id}/{dir}")
    Object busQueryBus(@PathVariable int id, @PathVariable int dir) {
        return BusApi.busQueryBus(id, dir);
    }

    @GetMapping("/nowBusStation/{busId}/{stationId}/{direction}")
    Object nowSameId3(
            @PathVariable String busId,
            @PathVariable String stationId,
            @PathVariable int direction
    ) {
        return BusApi.nowSameid3(busId, stationId, direction);
    }

    @GetMapping("/planRunTime/{busId}/{direction}")
    Object busPlanRunTime(
            @PathVariable int busId,
            @PathVariable int direction
    ) {
        return BusApi.busPlanRunTime(busId, direction);
    }

    @PostMapping("/iat")
    Object iat(@RequestParam("record") MultipartFile record){
        if (record.isEmpty()) {
            return "上传失败，请选择文件";
        }

        String fileName = record.getOriginalFilename();
        File dest = new File("d:/tmp/" + fileName);
        try {
            record.transferTo(dest);
            return "上传成功";
        } catch (IOException e) {
            System.out.println(e.toString());
        }

        return null;
    }
}
